let service_params_arr = [];

function _getserviceparams(a,callback){
	var one = a.shift();
	if(one){
		new service(`${CONST.TABLE_PREFIX}_params_browse_bynameandtype`).invoke(one).then((result)=>{
			if(result.length>0){
				service_params_arr.push(result[0]);
				_getserviceparams(a,callback);
			}else{
				new service(`${CONST.TABLE_PREFIX}_params_insert`).invoke(one).then(result=>{
          service_params_arr.push(result);
          _getserviceparams(a,callback);
        });
			}
		});
	}else{
		callback();
	}
}

function _get_service_params(){
  let serviceparams = params.serviceparams;
  if(serviceparams){
    serviceparams = serviceparams.split(',');
  }else{
    serviceparams = [];
  }
  let serviceparamsdata = [];
  for(let i=0,len=serviceparams.length;i<len;i++){
    let oneparam = serviceparams[i];
    if(/^__[a-z0-9_]+__[a-z0-9]+/gi.test(oneparam)){
      oneparam = oneparam.split('__');
      serviceparamsdata.push({name:oneparam[2],type:oneparam[1]});
    }else{
      serviceparamsdata.push({name:oneparam,type:'form'});
    }
  }
  return serviceparamsdata;
}

function _insert_service_params(serviceid){
  _getserviceparams(_get_service_params(),function(){
    for(let i=0,len=service_params_arr.length;i<len;i++){
      new service(`${CONST.TABLE_PREFIX}_service_param_insert`).invoke({serviceid:serviceid,paramid:service_params_arr[i].id,ordernum:(i+1)*5});
    }
  });
}

new service(`${CONST.TABLE_PREFIX}_service_browse`).invoke(params.id,params.id).then(result=>{
  if(result.length>0){
    let old = result[0];
    return new service(`${CONST.TABLE_PREFIX}_service_update`).invoke(params);
  }else{
    throw '没有找到相应数据！';
  }
}).then(result=>{
  return new service(`${CONST.TABLE_PREFIX}_service_params_delete_byserviceid`).invoke(params.id);
}).then(result=>{
  _insert_service_params(params.id);
  ret(null,'更新成功!');
}).catch(err=>{
  ret(err);
});